import logging
import sys
import redis
from . import config

# 加入日志
# 获取logger实例
logger = logging.getLogger("baseSpider")
# 指定输出格式
formatter = logging.Formatter('%(asctime)s\
              %(levelname)-8s:%(message)s')
# 文件日志
file_handler = logging.FileHandler("../logs/redis.log")
file_handler.setFormatter(formatter)
# 控制台日志
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)

# 为logge添加具体的日志处理器
logger.addHandler(file_handler)
logger.addHandler(console_handler)

logger.setLevel(logging.INFO)


class RedisConnector():
    # 构造函数,初始化数据库连接
    def __init__(self, db_num):
        self.connect_redis(db_num)

    def connect_redis(self, db_num):
        try:
            self.r = redis.StrictRedis(
                host=config.db_config['host'], port=config.db_config['port'], 
                password=config.db_config['password'], db=db_num,
                decode_responses=True)
            # self.r = redis.Redis(
            #     host=config.db_config['host'], port=config.db_config['port'], password=config.db_config['password'], db=db_num)
        except Exception as e:
            logger.error('redis连接失败，错误信息%s' % e)

    def lpush(self, key, value):
        self.r.lpush(key, value)

    def lpop(self, key):
        return self.r.lpop(key)

    def rpop(self, key):
        return self.r.rpop(key)

    def sismember(self, key, value):
        return self.r.sismember(key, value)

    def sadd(self, key, value):
        return self.r.sadd(key, value)

    def set(self, key, value):
        return self.r.set(key, value)

    def get(self, key):
        return self.r.get(key)

    def pipeline(self):
        return self.r.pipeline()
